/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Runtime.ExceptionServices;

#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

#if _LOCALDB
  namespace Oceanside.LocalDB
#else
namespace Oceanside.RemoteDB
#endif
{
    /// <summary>
    /// A user of the POS System.
    /// </summary>
    public partial class USER
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool HasAssignedRoles()
        {
            bool hasRoles = false;
            var q = from R in this.ROLES where R.IsDeleted == false select R;
            hasRoles = q.Any();
            if (!hasRoles)
            {
                UMD.ShowGuiMessageSTASafe_NOTHROW("You have logged in as a user whom does not have any defined roles.  Tell the manager that they need "
                    + "to assign a role to you before you can use this system.");
                return hasRoles;
            }
            return hasRoles;
        }
        public static bool IsValidEmailAddress(string email)
        {
            bool hasValidEmail = false;
            try
            {
                if (!String.IsNullOrEmpty(email))
                {
                    if (email.Contains('@'))
                    {
                        if (email.Contains('.'))
                        {
                            hasValidEmail = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return hasValidEmail;
        }

        public bool CheckForMagStripeRequirement()
        {
            var q = from R in SHIFT.GlobalContext.ROLES
                    where R.UserId == this.Id && !R.IsDeleted
                        && R.ACCESS_LEVEL.RequireMagcardLogin == true
                    select R;

            return q.Any();
        }
        public static string PopupSelectUser(out Int64 chosenDbId)
        {
            List<String> stringsList = new List<string>();
            List<Int64> pidsList = new List<Int64>();
            chosenDbId = DominicaEntities.CONST_ALL_DB_OBJECTS_WILDCARD;
            using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
            {
                var q = from USER in
                            context.USERS.Include("ROLES")
                            .Include("ROLES.ACCESS_LEVEL")
                            .Include("ROLES.PAYGRADE")
                            .Include("ROLES.JOB_CODE")
                        where USER.IsTerminated == false
                        orderby USER.UserName
                        select USER;

                if (q.Any())
                {
                    stringsList.Add("All Users");
                    pidsList.Add(DominicaEntities.CONST_ALL_DB_OBJECTS_WILDCARD);
                    foreach (USER user in q)
                    {
                        stringsList.Add(user.UserName);
                        pidsList.Add(user.Id);
                    }
                }
            }

            BoundObjectStringSelectionListBox dialog = new BoundObjectStringSelectionListBox(stringsList, pidsList);
            dialog.SetMessage("Select a username from the list and the system will only report data for that user.");
            dialog.ShowDialog();

            if (BoundObjectStringSelectionListBox.LastResponse == UserResponse.ENTER)
            {
                chosenDbId = BoundObjectStringSelectionListBox.ChosenDbId;
                return BoundObjectStringSelectionListBox.ChosenString;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="swipe"></param>
        /// <returns></returns>
        public static USER GetManagerForSwipe(string swipe)
        {
            try
            {
                var q = from USER in SHIFT.GlobalContext.USERS
                        where USER.LoginMagPassword == swipe &&
                            USER.IsTerminated == false
                        select USER;

                if (q.Any())
                {
                    USER user = q.First();
                    foreach (ROLE role in user.ROLES)
                    {
                        if (role.JOB_CODE != null && role.JOB_CODE.IsManager)
                        {
                            return user;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static String GetUsernameById(Int64 id)
        {
            String username = null;
            try
            {
                if (id != Int64.MaxValue)
                {
                    var query = from USER in SHIFT.GlobalContext.USERS where USER.Id == id select USER.UserName;
                    if (query.Count() != 0)
                    {
                        username = query.First();
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return username;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static String GetFirstNameLastNameById(Int64 id)
        {
            String name = null;
            if (id != Int64.MaxValue)
            {
                using (DominicaEntities objectContext = new DominicaEntities(DominicaEntities.GetEfConString()))
                {
                    objectContext.ContextOptions.LazyLoadingEnabled = false;
                    var query = from USER in objectContext.USERS where USER.Id == id select USER;
                    if (query.Count() != 0)
                    {
                        USER user = query.First();
                        name = user.FirstName + " " + user.LastName;
                    }
                }
            }
            return name;
        }


        public static SHIFT GetOpenSession(DominicaEntities objectContext, USER user)
        {
            var q = from VolatileTerminalSession in objectContext.SHIFTS
                    where VolatileTerminalSession.UserId == user.Id
                    select VolatileTerminalSession;
            if (q.Any())
            {
                return q.First();
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pword"></param>
        /// <returns></returns>
        public static USER ValidatePassword(String pword, bool isMagnetic)
        {
            USER loginUser = null;

            if (!String.IsNullOrEmpty(pword))
            {
                if (isMagnetic)
                {
                    var query = from USER in SHIFT.GlobalContext.USERS
                                where (USER.LoginMagPassword == pword && !USER.IsTerminated)
                                select USER;

                    if (query.Any())
                    {
                        loginUser = query.FirstOrDefault();
                    }
                }
                else
                {
                    try
                    {
                        ///Create the query object.
                        var query = from USER in SHIFT.GlobalContext.USERS
                                    where (USER.LoginKeyPassword == pword && !USER.IsTerminated)
                                    select USER;

                        if (query.Any())
                        {
                            loginUser = query.FirstOrDefault();
                        }
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
            else
            {
                Logging.LogMessage("The password string passed into ValidatePosKeypadLogin was null.");
            }
            return loginUser;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetUserNameStr(Int64 id, DominicaEntities context)
        {
            try
            {
                var q = from USER in context.USERS where USER.Id == id select USER.UserName;
                if (q.Count() != 0)
                {
                    return q.First().ToString();
                }
                else
                {
                    return "UNKNOWN";
                }
            }
            catch
            {
                return "UNKNOWN";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static USER GetUserById(Int64 id)
        {
            USER loginUser = null;
            try
            {
                ///Create the query object.
                var query = from USER in SHIFT.GlobalContext.USERS
                            where (USER.Id == id && !USER.IsTerminated)
                            select USER;

                ///This call will actually connect to the database and pull the data down.
                if (query.Count() != 0)
                {
                    ///This call will actually connect to the database and pull the data down.
                    loginUser = query.FirstOrDefault();
                }
            }
            catch
            {
                throw;
            }
            return loginUser;
        }


        #region Public Member Functions
        /// <summary>
        /// Status for setting the magnetic password of a user.
        /// </summary>
        public enum ENUM_SET_MAG_PWORD_STATUS
        {
            COMMUNICATION_ERROR,
            SUCCESS,
            PWORD_CURR_IN_USE
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pword"></param>
        /// <returns></returns>
        public ENUM_SET_MAG_PWORD_STATUS SetPosSwipeLogin(String pword)
        {
            ENUM_SET_MAG_PWORD_STATUS status = ENUM_SET_MAG_PWORD_STATUS.SUCCESS;
            using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
            {
                try
                {
                    var q = from USER in context.USERS
                            where USER.IsTerminated == false &&
                                USER.LoginMagPassword.Equals(pword) && USER.Id != this.Id
                            select USER;

                    if (q.Any())
                    {
                        status = ENUM_SET_MAG_PWORD_STATUS.PWORD_CURR_IN_USE;
                    }
                    else
                    {
                        this.LoginMagPassword = pword;
                        object o;
                        context.TryGetObjectByKey(this.EntityKey, out o);
                        (o as USER).LoginMagPassword = pword;
                        context.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    Logging.LogException(e);
                    status = ENUM_SET_MAG_PWORD_STATUS.COMMUNICATION_ERROR;
                }
            }
            return status;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="pword"></param>
        /// <returns></returns>
        public bool CanSetMagStripe()
        {
            bool canAdd = false;
            System.Data.Objects.DataClasses.EntityCollection<ROLE> roles = this.ROLES;
            foreach (ROLE role in roles)
            {
                if (!role.IsDeleted && role.ACCESS_LEVEL.CanSetMagStripe)
                {
                    canAdd = true;
                }
            }
            return canAdd;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (this.FirstName != null)
                return this.LastName + ", " + this.FirstName;
            else
                return "";
        }

        #endregion Public Member Functions
    }

}
